# -*- coding: UTF-8 -*-

import pygame
from utils import *
from movable import Movable

global Game
class BurningTile(pygame.sprite.Sprite, Movable):
    size = 20
    energyColor = {}

    def __init__(self, pos, *args, **kwargs):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([self.size, self.size])
        self.rect = self.image.get_rect()
        self.rect.topleft = pos

        self.x = self.rect.topleft[0] + self.rect.w/2
        self.y = self.rect.topleft[1] + self.rect.h/2

        Movable.__init__(self, (self.x, self.y), *args)
        if "energy" in kwargs:
            self.energy = kwargs["energy"]
        else:
            self.energy = intRandom(100) + 200 #300

    def getNeighbours(self):
        x,y = self.pos
        return [ (x-1,y-1), (x,y-1), (x+1,y-1),
                 (x-1,y),            (x+1,y),
                 (x-1,y+1), (x,y+1), (x+1,y+1), ]

    def move(self, time_passed):
        Movable.move(self, time_passed)
        self.x -= (intRandom(18) - 9) * time_passed * 0.0625 / 2
        self.y -= (intRandom(20) - 6) * time_passed * 0.0625 / 2


        if self.energy > 200:
            self.energy -= 2 * time_passed * 0.0625
        else:
            self.energy -= 3 * time_passed * 0.0625
        if not intRandom(5):
            self.energy -= intRandom(5)
        self.energy = int(self.energy)

        if self.energy < -50:
            self.kill()
        return

    def draw(self, camera):
        rect = self.image.get_rect()
        rect.topleft = (self.x - self.rect.w / 2, self.y - self.rect.h / 2)

        self.image, self.color = BurningTile.energyColor[Clamp(self.energy, 0, 300)]
        camera.blit(self.image, rect)
        return

    @staticmethod
    def precalculateEnergyLevelColors():
        def computeLine(x0,x1,y0,y1,x):  
            if x0==x1:
                return (y0+y1)//2
            return y0-(x0-x)*(y1-y0)//(x1-x0)
        milestones = [[214, 232, 233],
                      [255, 253, 107],
                      [255, 165, 79],
                      [255,69,0],
                      [238, 64, 0],
                      [0,0,0]]
        energyThresholds=[300,290,240,150,90,0]
        for energy in range(0, 300 +1):
            for i in range(len(energyThresholds)-1):
                if (energyThresholds[i] >= energy >= energyThresholds[i+1]):
                    color = [computeLine(
                            energyThresholds[i],
                            energyThresholds[i+1],
                            milestones[i][j],
                            milestones[i+1][j],
                            energy) for j in range(0,3)]
                    
                    col = pygame.color.Color(*color)
                    im = pygame.Surface([BurningTile.size, BurningTile.size])
                    im.fill(col)
                    BurningTile.energyColor[energy]= (im, col)
                    break
